// import Compressor from 'compressorjs';
// import SparkMD5 from 'spark-md5';
import { Dialog, Toast as showToast } from 'vant';

/**
 * 判断传入的变量是否是一个dom对象
 */
export function isDom (dom) {
  return (typeof HTMLElement === 'object')
    ? (dom instanceof HTMLElement)
    : (dom && typeof dom === 'object' && dom.nodeType === 1 && typeof dom.nodeName === 'string');
}

/**
 * 判断数据的具体类型
 */
export function type (mixin) {
  if (mixin == null) {
    return String(mixin);
  }
  const class2type = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regexp',
    '[object Object]': 'object',
    '[object Error]': 'error',
    '[object Symbol]': 'symbol',
    '[object File]': 'file'
  };

  const mixinType = typeof mixin;
  if (mixinType === 'undefined') {
    return 'undefined';
  }
  if (mixinType === 'object' || mixinType === 'function') {
    const _type = class2type[toString.call(mixin)];

    if (!_type) {
      return isDom(mixin) ? 'dom' : 'object';
    }

    return _type;
  }

  return mixinType;
}

/**
 * 是否为空值，不包括0
 */
export function isEmpty (mixin) {
  const _type = type(mixin);
  if (_type === 'number' && isNaN(mixin)) {
    return true;
  }
  if (['null', 'undefined'].includes(_type)) {
    return true;
  }
  if (_type === 'boolean' && mixin === false) {
    return true;
  }
  if (_type === 'array' && mixin.length === 0) {
    return true;
  }
  if (_type === 'file') {
    return false;
  }
  if (_type === 'object' && Object.keys(mixin).length === 0) {
    return true;
  }
  return mixin === '';
}

/**
 * 符合 type() 函数的验证，如果验证不成功适用默认值
 */
export function defaults (mixin, def = '', compareFunction = isEmpty) {
  return compareFunction(mixin) ? def : mixin;
}

/**
 * 数字类型转换为字符串（其他情况保留）
 */
export function transString (value) {
  return typeof value === 'number' ? String(value) : value;
}

export function loading (message = '加载中') {
  return showToast.loading({
    duration: 0,
    message: message,
    forbidClick: true
  });
}

export function loadingDone () {
  return showToast.clear();
}

export function toast (text, onClose) {
  return showToast({
    message: text,
    position: 'bottom',
    onClose
  });
}

export function successToast (text, onClose) {
  return showToast({
    type: 'success',
    message: text,
    forbidClick: true,
    onClose
  });
}

export function errorToast (text, options = {}) {
  return showToast(Object.assign({
    type: 'fail',
    message: text,
    forbidClick: true
  }, options));
}

export function alertDialog (text, options = {}) {
  return Dialog.alert(Object.assign({
    message: text
  }, options));
}

export function confirmDialog (text, options = {}) {
  return Dialog.confirm(Object.assign({
    message: text
  }, options));
}



export function hasOwn (object, key) {
  return Object.prototype.hasOwnProperty.call(object, key);
}

/**
 * 生成随机id
 */
export function randomId (len = 32) {
  // const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  const $chars = 'abcdef0123456789'; /** **只获取16进制可访问字符****/
  const maxPos = $chars.length;
  let pwd = '';

  // eslint-disable-next-line no-unmodified-loop-condition
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }

  return pwd;
}

/**
 * 人性化显示文件大小
 */
export function byteSize (size) {
  // 判断b
  if (size < 1024) {
    return size + 'byte';
  }

  // 判断kb
  size = (size / 1024).toFixed(2);

  if (size < 1024) {
    return size + 'KB';
  }

  // 判断mb
  size = (size / 1024).toFixed(2);

  if (size < 1024) {
    return size + 'MB';
  }

  // 判断gb
  size = (size / 1024).toFixed(2);

  if (size < 1024) {
    return size + 'GB';
  }

  // tb
  size = (size / 1024).toFixed(2);

  return size + 'TB';
}

/**
 * base64转blob
 */
export function base642Blob (base64Data) {
  let byteString;

  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = atob(base64Data.split(',')[1]);
  } else {
    byteString = unescape(base64Data.split(',')[1]);
  }
  const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  const ia = new Uint8Array(byteString.length);

  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  return new Blob([ia], {
    type: mimeString
  });
}

/**
 * blob转file
 */
export function blob2File (blob, name, options = {}) {
  // blob.lastModifiedDate = new Date();
  // blob.name = name;
  // return blob;
  options = Object.assign({
    type: 'image/jpg'
  }, options);

  return new File([blob], name, options);
}

/**
 * @param {string} str 去除html标签
 */
export function removeHTMLTag (str) {
  str = str.replace(/<\/?[^>]*>/g, ''); // 去除HTML tag
  str = str.replace(/[ | ]*\n/g, '\n'); // 去除行尾空白
  str = str.replace(/\n[\s| | ]*\r/g, '\n'); // 去除多余空行
  str = str.replace(/ /ig, ''); // 去掉
  const arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' }; // 转义符换成普通字符

  str = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  });

  return str;
}

const slice = Array.prototype.slice;

export function like2Array (likeArray) {
  return slice.call(likeArray);
}

export function isWechatDevice () {
  const ua = window.navigator.userAgent.toLowerCase();

  return Boolean(ua.match(/MicroMessenger/i) === 'micromessenger');
}

/**
 * 获取当前设备类型
 */
export function device () {
  const userAgentInfo = navigator.userAgent;
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
  let flag = true;
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  // 如果未找到以上标识，视为pc端
  if (flag) {
    return 'pc';
  }
  // 安卓
  if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {
    return 'android';
  }
  // iOS
  if (userAgentInfo.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return 'ios';
  }
  return 'unknown';
}
